package com.ruoyi.web.plan.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.web.plan.domain.*;
import com.ruoyi.web.plan.service.IDutyService;
import com.ruoyi.web.plan.service.IProjectService;
import com.ruoyi.web.plan.service.ITaskInfoService;
import com.ruoyi.web.system.domain.SysUser;
import com.ruoyi.web.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.utils.poi.ExcelUtil;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 项目信息Controller
 *
 * @author ruoyi
 * @date 2024-11-30
 */
@RestController
@RequestMapping("/project/info")
public class ProjectController extends BaseController {
    @Autowired
    private IProjectService projectService;

    @Autowired
    private ITaskInfoService taskInfoService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDutyService dutyService;

    /**
     * 查询项目信息列表
     */
    @SaCheckPermission("project:info:list")
    @GetMapping("/list")
    public TableDataInfo list(Project project) {
        startPage();
        List<Project> list = projectService.selectProjectList(project);
        return getDataTable(list);
    }

    /**
     * 查询项目信息列表
     */
    @SaCheckPermission("project:info:list")
    @GetMapping("/board")
    public AjaxResult listBoard() {
        List<Project> projectList = projectService.selectProjectList(null);
        List<TaskInfo> taskList = taskInfoService.selectTaskInfoList(null);
        List<Duty> dutyList = dutyService.selectDutyList(null);
        logger.debug("============" + taskList);
        //
        List<ProjectProgress> projectProgressList = new ArrayList<>();
        for (Project proItem : projectList) {
            ProjectProgress progress = new ProjectProgress();
            progress.setProjectId(proItem.getProjectId());
            progress.setProjectName(proItem.getProjectName());
            progress.setState(proItem.getState());
            progress.setStartTime(proItem.getStartTime());
            progress.setEndTime(proItem.getEndTime());
            //
            int taskFinishCount = 0;
            int totalCount = 0;
            for (TaskInfo taskItem : taskList) {
                if (Objects.equals(proItem.getProjectId(), taskItem.getProjectId())) {
                    totalCount = totalCount + 1;
                    //完成状态
                    if (taskItem.getRunState().equalsIgnoreCase("3")) {
                        taskFinishCount = taskFinishCount + 1;
                    }
                }
            }
//            logger.debug("============totalCount  " + totalCount);
//            logger.debug("============taskFinishCount  " + taskFinishCount);
            progress.setTaskTotalCount(totalCount);
            progress.setTaskFinishCount(taskFinishCount);

            BigDecimal useTime = BigDecimal.valueOf(0);
            for (Duty duty : dutyList) {
                if (Objects.equals(proItem.getProjectId(), duty.getProjectId())) {
                    if (duty.getUseTime() != null) {
                        logger.debug("============getUseTime  " + duty.getUseTime());
                        useTime = useTime.add(duty.getUseTime());
                    }
                }
            }
            progress.setUseTime(useTime);
            projectProgressList.add(progress);
        }
        return AjaxResult.success(projectProgressList);
    }


    /**
     * 查询项目信息列表
     */
    @SaCheckPermission("project:info:list")
    @GetMapping("/userStatistics")
    public AjaxResult userStatistics() {
        List<Project> projectList = projectService.selectProjectList(null);
        List<TaskInfo> taskList = taskInfoService.selectTaskInfoList(null);
        List<SysUser> userList = userService.selectUserList(new SysUser());
        List<Duty> dutyList = dutyService.selectDutyList(null);
        //
        List<UserTaskStatistics> userTaskStatistics = new ArrayList<>();
        for (Project proItem : projectList) {
            UserTaskStatistics statistics = new UserTaskStatistics();
            statistics.setProject(proItem);
            userTaskStatistics.add(statistics);
        }

        for (UserTaskStatistics item : userTaskStatistics) {
            item.setUserList(new ArrayList<>());
            for (SysUser user : userList) {
                if (item.getProject().getUserIdList().contains(user.getUserId())) {
                    ProjectUser projectUser = new ProjectUser();
                    projectUser.setUserId(user.getUserId());
                    projectUser.setUserName(user.getNickName());
                    projectUser.setDeptId(user.getDeptId());
                    projectUser.setDeptName(user.getDept().getDeptName());
                    item.getUserList().add(projectUser);
                }
            }
        }

        //计算每个人的任务总数和任务完成数
        for (UserTaskStatistics item : userTaskStatistics) {
            for (ProjectUser user : item.getUserList()) {
                getUserTask(taskList, item.getProject().getProjectId(), user);
            }
        }

        //计算每个人的任务耗时
        for (UserTaskStatistics item : userTaskStatistics) {
            for (ProjectUser user : item.getUserList()) {
                BigDecimal useTime = getUserTimeByUser(dutyList, item.getProject().getProjectId(), user);
                user.setUseTime(useTime);
            }
        }
        return AjaxResult.success(userTaskStatistics);
    }

    private void getUserTask(List<TaskInfo> taskList, Long projectId, ProjectUser user) {
        if (taskList == null || taskList.isEmpty()) {
            return;
        }
        int totalCount = 0;
        int finishCount = 0;
        for (TaskInfo taskInfo : taskList) {
            if (Objects.equals(projectId, taskInfo.getProjectId()) && Objects.equals(taskInfo.getAssignUserId(), user.getUserId())) {
                totalCount = totalCount + 1;
                //任务已完成
                if (taskInfo.getRunState().equalsIgnoreCase("3")) {
                    finishCount = finishCount + 1;
                }
            }
        }
        user.setFinishTask(finishCount);
        user.setTotalTask(totalCount);
        logger.debug("============getUserTask  " + user.getUserName() + "任务：" + user.getFinishTask() + "/" + user.getTotalTask());
    }

    private BigDecimal getUserTimeByUser(List<Duty> dutyList, Long projectId, ProjectUser user) {
        if (dutyList == null || dutyList.isEmpty()) {
            return BigDecimal.valueOf(0);
        }
        BigDecimal useTime = BigDecimal.valueOf(0);
        for (Duty duty : dutyList) {
            if (Objects.equals(projectId, duty.getProjectId()) && Objects.equals(duty.getUserId(), user.getUserId())) {
                if (duty.getUseTime() != null) {
                    logger.debug("============getUseTime  " + duty.getUseTime());
                    useTime = useTime.add(duty.getUseTime());
                }
            }
        }
        return useTime;
    }


    /**
     * 导出项目信息列表
     */
    @SaCheckPermission("project:info:export")
    @Log(title = "项目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Project project) {
        List<Project> list = projectService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        util.exportExcel(response, list, "项目信息数据");
    }

    /**
     * 获取项目信息详细信息
     */
    @SaCheckPermission("project:info:query")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId) {
        return success(projectService.selectProjectByProjectId(projectId));
    }


    /**
     * 新增项目信息
     */
    @SaCheckPermission("project:info:add")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Project project) {
        return toAjax(projectService.insertProject(project));
    }

    /**
     * 修改项目信息
     */
    @SaCheckPermission("project:info:edit")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Project project) {
        return toAjax(projectService.updateProject(project));
    }

    /**
     * 删除项目信息
     */
    @SaCheckPermission("project:info:remove")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds) {
        return toAjax(projectService.deleteProjectByProjectIds(projectIds));
    }
}
